<template>
  <div class="question-list">
    <el-empty v-if="!questions.length" description="暂无问题" />
    
    <el-card
      v-else
      v-for="item in questions"
      :key="item.id"
      class="question-card"
      :class="{ 'is-collected': item.isCollected }"
    >
      <template #header>
        <div class="question-header">
          <h3>{{ item.question }}</h3>
          <div class="question-tags">
            <el-tag v-if="item.isLearned" type="success" effect="dark">
              <el-icon><Check /></el-icon> 已学会
            </el-tag>
            <el-tag type="warning">
              难度: {{ item.difficulty }}
            </el-tag>
            <el-button
              :type="item.isCollected ? 'warning' : 'default'"
              size="small"
              @click="toggleCollect(item.id)"
            >
              <el-icon><Star /></el-icon>
              {{ item.isCollected ? '取消收藏' : '收藏' }}
            </el-button>
          </div>
        </div>
      </template>
      
      <div class="answer-content">
        <div class="answer-wrapper" :class="{ 'is-loading': item.regenerating }">
          <div class="editor-container">
            <Editor
              :defaultConfig="editorConfig"
              :defaultHtml="formatAnswer(item.answer)"
              :mode="'default'"
              :style="{height: 'auto', overflowY: 'hidden'}"
              @onCreated="handleCreated"
            />
          </div>
          <div v-if="item.regenerating" class="loading-mask">
            <el-icon class="loading-icon" :size="30"><Loading /></el-icon>
            <span>正在更新答案...</span>
            <el-button 
              type="text" 
              class="cancel-btn"
              @click="cancelRegenerate(item.id)"
            >
              取消更新
            </el-button>
          </div>
        </div>
        
        <div class="action-buttons">
          <el-button-group>
            <el-button
              type="primary"
              size="small"
              @click="regenerateAnswer(item.id)"
              :loading="item.regenerating"
              :disabled="item.regenerating"
            >
              <el-icon><Refresh /></el-icon>
              {{ item.regenerating ? '更新中' : '重新生成' }}
            </el-button>
            <el-button
              :type="item.isLearned ? 'success' : 'default'"
              size="small"
              @click="toggleLearned(item.id)"
            >
              <el-icon><Check /></el-icon>
              {{ item.isLearned ? '已掌握' : '标记为已学会' }}
            </el-button>
          </el-button-group>
          
          <el-rate
            v-model="item.difficulty"
            :max="5"
            @change="updateDifficulty(item.id, $event)"
          />
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { computed, onMounted, shallowRef } from 'vue'
import { Star, Check, Refresh, Loading } from '@element-plus/icons-vue'
import { useQuestionStore } from '../stores/question'
import { ElMessage } from 'element-plus'
import '@wangeditor/editor/dist/css/style.css'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import hljs from 'highlight.js'
import 'highlight.js/styles/atom-one-dark.css'

const questionStore = useQuestionStore()
const questions = computed(() => questionStore.questions)
const editor = shallowRef()

// 编辑器配置
const editorConfig = {
  readOnly: true,
  autoFocus: false,
  scroll: false,
  MENU_CONF: {
    codeBlock: {
      highlightjs: hljs,
      languageList: [
        { text: 'Java', value: 'java' },
        { text: 'JavaScript', value: 'javascript' },
        { text: 'HTML', value: 'html' },
        { text: 'CSS', value: 'css' },
        { text: 'Python', value: 'python' },
        { text: 'SQL', value: 'sql' },
        { text: 'Bash', value: 'bash' },
        { text: 'Plain Text', value: 'plaintext' }
      ]
    }
  }
}

// 处理编辑器创建完成
const handleCreated = (e) => {
  editor.value = e
}

const formatAnswer = (answer) => {
  if (!answer) return ''
  
  // 处理代码块
  const formattedContent = answer.replace(/```(\w*)([\s\S]*?)```/g, (match, language, code) => {
    language = language.trim() || 'plaintext'
    code = code.trim()
    return `<pre><code class="language-${language}">${code}</code></pre>`
  })

  // 处理普通文本段落
  return formattedContent.split('\n').map(line => {
    if (line.trim() && !line.includes('<pre><code')) {
      return `<p>${line}</p>`
    }
    return line
  }).join('\n')
}

onMounted(() => {
  questionStore.fetchQuestions()
})

const toggleCollect = async (id) => {
  try {
    await questionStore.toggleCollect(id)
    ElMessage.success('操作成功')
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const toggleLearned = async (id) => {
  try {
    await questionStore.toggleLearned(id)
    ElMessage.success('操作成功')
  } catch (error) {
    ElMessage.error('操作失败')
  }
}

const regenerateAnswer = async (id) => {
  try {
    await questionStore.regenerateAnswer(id)
    ElMessage.success('答案已更新')
  } catch (error) {
    ElMessage.error('重新生成失败')
  }
}

const updateDifficulty = async (id, value) => {
  try {
    await questionStore.updateDifficulty(id, value)
    ElMessage.success('难度已更新')
  } catch (error) {
    ElMessage.error('更新失败')
  }
}

const cancelRegenerate = (id) => {
  const question = questionStore.questions.find(q => q.id === id)
  if (question) {
    question.regenerating = false
    ElMessage.info('已取消更新')
  }
}
</script>

<style scoped>
.question-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.question-card {
  border-radius: 8px;
  transition: all 0.3s ease;
}

.question-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.is-collected {
  border: 1px solid #e6a23c;
}

.question-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  gap: 20px;
}

.question-header h3 {
  margin: 0;
  font-size: 16px;
  color: #303133;
}

.question-tags {
  display: flex;
  gap: 10px;
  align-items: center;
}

.answer-content {
  padding: 20px;
  background: #ffffff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.answer-wrapper {
  position: relative;
  min-height: 100px;
}

.answer-wrapper.is-loading .editor-container {
  opacity: 0.5;
  filter: blur(1px);
}

.loading-mask {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: rgba(255, 255, 255, 0.9);
  backdrop-filter: blur(2px);
  z-index: 1;
}

.loading-icon {
  animation: rotate 1s linear infinite;
  margin-bottom: 10px;
  color: #409EFF;
}

.loading-mask span {
  color: #409EFF;
  font-size: 14px;
}

@keyframes rotate {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

.cancel-btn {
  margin-top: 10px;
  color: #909399;
}

.cancel-btn:hover {
  color: #409EFF;
}

.editor-container {
  border: none;
}

:deep(.w-e-text-container) {
  background: transparent !important;
  border: none !important;
}

:deep(.w-e-text-container [data-slate-editor]) {
  padding: 0 !important;
}

:deep(.w-e-text-container p) {
  margin: 8px 0;
  line-height: 1.6;
}

:deep(.w-e-text-container pre) {
  background-color: #282c34;
  border-radius: 6px;
  margin: 16px 0;
}

:deep(.w-e-text-container pre code) {
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', monospace;
  font-size: 14px;
  line-height: 1.5;
}

:deep(.w-e-text-container blockquote) {
  border-left: 4px solid #dfe2e5;
  padding: 0 1em;
  color: #6a737d;
  margin: 1em 0;
}

:deep(.w-e-text-container ul),
:deep(.w-e-text-container ol) {
  padding-left: 2em;
  margin: 0.8em 0;
}

:deep(.w-e-text-container li) {
  margin: 0.3em 0;
}

.action-buttons {
  margin-top: 15px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
</style> 